package com.withmiku.world.user.controller;

import com.withmiku.world.user.common.Result;
import com.withmiku.world.user.dto.PostCreateDto;
import com.withmiku.world.user.entity.Post;
import com.withmiku.world.user.entity.PostImage;
import com.withmiku.world.user.entity.User;
import com.withmiku.world.user.service.PostService;
import com.withmiku.world.user.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/user/post")
public class PostController {
    private final PostService postService;
    private final UserService userService;
    @Value("${file.upload-dir:uploads}")
    private String uploadRootPath;

    @Autowired
    public PostController(PostService postService,
                          @Qualifier("userServiceImpl") UserService userService) {
        this.postService = postService;
        this.userService = userService;
    }

    /**
     * 发表动态/专栏
     */
    @PostMapping("/create")
    public Result<Post> createPost(@RequestBody PostCreateDto dto,
                                HttpServletRequest request) {
        String username = (String)request.getAttribute("username");
        User user = userService.findByUsername(username);

        Post post = new Post();
        post.setUserId(user.getId());
        post.setType(dto.getType());
        post.setTitle(dto.getTitle());
        post.setContent(dto.getContent());

        // 封装图片
        if (dto.getImages() != null) {
            List<PostImage> images = dto.getImages().stream().map(imageDto -> {
                PostImage image = new PostImage();
                image.setUrl(imageDto.getUrl());
                image.setSortOrder(imageDto.getSortOrder());
                return image;
            }).toList();
            post.setImages(images);
        }
        Post saved = postService.createPost(post);

        return Result.success(200, "发表成功", saved);
    }

    /**
     * 分页查询动态（所有人可见）
     */
    @GetMapping("/list")
    public Result listPosts(@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer size) {
        // 注意服务层的page从0开始是第一页，需要在这里进行减1处理
        int pageIndex = page - 1;
        if (pageIndex < 0) {
            pageIndex = 0;
        }

        Page<Post> result = postService.listPosts(pageIndex, size);
        return Result.success(200, "查询成功", result);
    }

    /**
     * 查看动态/专栏详情
     */
    @GetMapping("/{id}")
    public Result<Post> getPostDetail(@PathVariable Long id) {
        Post post = postService.getPostById(id);
        return Result.success(200, "查询成功", post);
    }

    /**
     * 查看某个用户的所有动态/专栏（查看自己的和别人的都用这一个接口）
     */
    @GetMapping("/user/{userId}")
    public Result listUserPosts(@PathVariable Long userId,
                                   @RequestParam(defaultValue = "1") Integer page,
                                   @RequestParam(defaultValue = "10") Integer size) {
        int pageIndex = page - 1;
        if (pageIndex < 0) {
            pageIndex = 0;
        }

        Page<Post> result;
        result = postService.getUserPosts(userId, pageIndex, size);

        return Result.success(200, "查询成功", result);
    }

    /**
     * 动态图片上传接口
     */
    @PostMapping("/upload")
    public Result uploadImages(@RequestPart("file") MultipartFile[] files,
                                  HttpServletRequest request) {
        if (files == null || files.length == 0) {
            return Result.error("文件不存在，请上传文件");
        }

        String username = (String)request.getAttribute("username");

        List<String> urls = new ArrayList<>();

        // 日期分目录
        LocalDate today = LocalDate.now();
        String datePath = today.getYear() + "/" + today.getMonth() + "/" + today.getDayOfMonth();

        // 最终存储路径
        String fullPath = uploadRootPath + "/posts/" + datePath;

        File dir = new File(fullPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        for (MultipartFile file : files) {
            try {
                String originalName = file.getOriginalFilename();
                String ext = "";

                // 获取扩展名
                // TODO 按照扩展名删选文件，防止恶意文件入侵
                int index = originalName.lastIndexOf(".");
                if (index != -1) {
                    ext = originalName.substring(index);
                }

                // 生成唯一文件名(userId_timestamp_originalFilename)
                Long userId = userService.findByUsername(username).getId();
                String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                String filename = userId + "_" + timestamp + "_" + originalName;

                File dest = new File(dir, filename);
                file.transferTo(dest);

                // 返回前端的 URL，例如：/uploads/posts/2025/11/18/xxx.jpg
                String url = "/uploads/posts/" + datePath + "/" + filename;
                urls.add(url);
            } catch (IOException e) {
                return Result.error("上传失败" + e.getMessage());
            }
        }

        return Result.success(200, "上传成功", urls);
    }
}
